# 导入必要的库和模块
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import font_manager
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
import pickle
from tqdm import tqdm 

# 设置自定义字体
font_path = "D:\homework\SimHei.ttf"
font_prop = font_manager.FontProperties(fname=font_path)

# 加载手写数字数据集
digits = load_digits()
X, y = digits.data, digits.target

# 将数据集划分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# 初始化变量以存储最佳准确率，相应的k值和最佳knn模型
best_accuracy = 0
best_k = 0
best_knn_model = None

# 初始化一个列表以存储每个k值的准确率
accuracies = []

# 尝试从1到40的k值，对于每个k值，训练knn模型，保存最佳准确率，k值和knn模型
print("训练过程进度：")
for k in tqdm(range(1, 41,2), desc="正在尝试不同的k值"):
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train, y_train)
    y_pred = knn.predict(X_test)
    accuracy = accuracy_score(y_test, y_pred)
    accuracies.append(accuracy)

    if accuracy > best_accuracy:
        best_accuracy = accuracy
        best_k = k
        best_knn_model = knn

# 将最佳KNN模型保存到二进制文件
with open('best_knn_model.pkl', 'wb') as file:
    pickle.dump(best_knn_model, file)

# 打印最佳准确率和相应的k值
print(f"最佳准确率: {best_accuracy:.4f}, 最佳的k值: {best_k}")

# 生成PDF文件，显示准确率变化
plt.figure(figsize=(10, 6))
plt.plot(range(1, 41,2), accuracies, marker='o', label='准确率')
plt.axvline(x=best_k, color='red', linestyle='--', label=f'最佳k值: {best_k}')
plt.scatter([best_k], [best_accuracy], color='red') # 标记最佳准确率的点
plt.text(best_k, best_accuracy, f'k={best_k}, Acc={best_accuracy:.4f}', verticalalignment='bottom', horizontalalignment='right', fontproperties=font_prop)
plt.xlabel('k值', fontproperties=font_prop)
plt.ylabel('准确率', fontproperties=font_prop)
plt.title('K值与模型准确率的关系', fontproperties=font_prop)
plt.legend(prop=font_prop)
plt.grid(True)
plt.savefig('accuracy_plot.pdf', bbox_inches='tight')
plt.show()
